const OSS = require('ali-oss');

// 阿里云OSS配置
const ossConfig = {
  region: 'oss-cn-hongkong',
  accessKeyId: 'LTAI5t71WWvDnNdYJ7yeq8hT',
  accessKeySecret: '95QtIhIxwnwJVBVqYrBmrAgjnZoewZ',
  bucket: 'dkd-muxiu',
  endpoint: 'oss-cn-hongkong.aliyuncs.com'
};

// 创建OSS客户端
const client = new OSS(ossConfig);

// 上传文件到OSS
async function uploadToOSS(buffer, fileName, contentType = 'image/jpeg') {
  try {
    // 生成日期格式 yyyy-MM-dd
    const now = new Date();
    const year = now.getFullYear();
    const month = String(now.getMonth() + 1).padStart(2, '0');
    const day = String(now.getDate()).padStart(2, '0');
    const dateStr = `${year}-${month}-${day}`;
    
    // 生成带日期的文件名
    const timestamp = Date.now();
    const objectName = `travel-images/${dateStr}/${timestamp}-${fileName}`;
    
    const result = await client.put(objectName, buffer, {
      headers: {
        'Content-Type': contentType,
        'Cache-Control': 'public, max-age=31536000' // 缓存一年
      }
    });

    // 返回完整的访问URL
    const url = `https://dkd-muxiu.oss-cn-hongkong.aliyuncs.com/${objectName}`;
    
    console.log('文件上传成功:', url);
    
    return {
      success: true,
      url: url,
      objectName: objectName,
      size: buffer.length
    };
  } catch (error) {
    console.error('OSS上传失败:', error);
    return {
      success: false,
      error: error.message
    };
  }
}

// 删除OSS文件
async function deleteFromOSS(objectName) {
  try {
    await client.delete(objectName);
    console.log('文件删除成功:', objectName);
    return { success: true };
  } catch (error) {
    console.error('OSS删除失败:', error);
    return { success: false, error: error.message };
  }
}

module.exports = {
  client,
  uploadToOSS,
  deleteFromOSS
};